package com.hmdp.config;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @Author dlc
 * @Date 2023/11/13
 * @Description TODO
 * @Version 0.0.1
 */
public class SimpleLock implements ILock{

    private String lockName;

    private StringRedisTemplate stringRedisTemplate;

    public SimpleLock(String lockName, StringRedisTemplate stringRedisTemplate) {
        this.lockName = lockName;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    private static final String LOCK_PREFIX = "lock:";
    private static final String ID_PREFIX = UUID.randomUUID().toString(true) + "-";

    // 用来读取lua脚本
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        // 初始化
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        // 加载lua脚本
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        // 设置结果类型
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    @Override
    public boolean tryLock(long timeout) {
        // 获取当前线程的标识
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        // 加锁
        Boolean success = stringRedisTemplate.opsForValue()
                .setIfAbsent(LOCK_PREFIX + lockName, threadId,
                timeout, TimeUnit.SECONDS);
        // 注意这种拆箱方式
        return Boolean.TRUE.equals(success);
    }

    /**
     * lua实现unlock
     */
    @Override
    public void unLock() {
        // 调用lua脚本
        stringRedisTemplate.execute(UNLOCK_SCRIPT,
                Collections.singletonList(LOCK_PREFIX + lockName) ,
                ID_PREFIX + Thread.currentThread().getId());
    }

/*    public void unLock() {

        String threadId = ID_PREFIX + Thread.currentThread().getId();
        // 获取这个key
        String cacheThreadId = stringRedisTemplate.opsForValue().get(LOCK_PREFIX + lockName);
        if(threadId.equals(cacheThreadId)) {
            // 释放锁
            stringRedisTemplate.delete(LOCK_PREFIX + lockName);
        }
    }*/
}
